package com.sunjob.mrogeteway.filter;

import com.alibaba.fastjson.JSON;
import com.sunjob.common.result.Result;
import com.sunjob.mrosystem.bucketLimit.MROBucketLimit;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Wangzurong
 * @create 2022-08-04 22:26
 */
public class MROQpsPartLimiterFilter implements GatewayFilter , Order {
    private int qpsVal;
    private int qpsSplit;
    private MROBucketLimit mroBucketLimit;
    public MROQpsPartLimiterFilter(int qpsVal,int qpsSplit){
        this.qpsVal = qpsVal;
        this.qpsSplit = qpsSplit;
        this.mroBucketLimit = new MROBucketLimit(qpsVal);
        Runnable runnable = () -> {
            // 平滑添加令牌
            mroBucketLimit.put(qpsVal / qpsSplit);
        };
        // 每隔100ms添加value/qpsSplit 个令牌 在1s后执行
        MROScheduleSingleTask.getService().scheduleAtFixedRate(runnable, 1000, 1000/qpsSplit, TimeUnit.MILLISECONDS);
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (!mroBucketLimit.acquire()) {
            // 被限流 返回错误信息
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(Result.fail("服务器暂时繁忙，请稍后再试")));
            return response.writeWith(Mono.just(dataBuffer));
        } else {
            // 成功获得令牌
            return chain.filter(exchange);
        }
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }

    @Override
    public int value() {
        return 0;
    }
}
